<script setup>
import { onMounted, ref } from "vue";
import {
  queryPageApi,
  addApi,
  getByIdApi,
  updateApi,
  deleteApi,
  getDeptListApi,
  getRoleListApi,
} from "@/api/user";
import { ElMessage, ElMessageBox } from "element-plus";

const queryParams = ref({
  name: "",
  phone: "",
  deptId: "",
  status: "",
  page: 1,
  pageSize: 10,
});
const total = ref(0);
const userList = ref([]);
const deptList = ref([]);
const roleList = ref([]);
const selectedUsers = ref([]);

const search = async () => {
  const result = await queryPageApi(queryParams.value);
  if (result.code == 1) {
    userList.value = result.data.rows;
    total.value = result.data.total;
  }
};

const clear = () => {
  queryParams.value = {
    name: "",
    phone: "",
    deptId: "",
    status: "",
    page: 1,
    pageSize: 10,
  };
  search();
};

const getDeptList = async () => {
  const result = await getDeptListApi();
  if (result.code == 1) {
    deptList.value = result.data;
  }
};

const handleUploadSuccess = (response) => {
  if (response.code === 1) {
    form.value.image = response.data;
    ElMessage.success("上传成功");
  } else {
    ElMessage.error(response.msg || "上传失败");
  }
};

const getRoleList = async () => {
  const result = await getRoleListApi();
  if (result.code == 1) {
    roleList.value = result.data;
  }
};
const token = ref("");
onMounted(() => {
  getDeptList();
  getRoleList();
  search();

  token.value = localStorage.getItem("token");
});

const handleSizeChange = (val) => {
  search();
};

const handleCurrentChange = (val) => {
  search();
};

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection;
};

// 添加用户表单
const dialogFormVisible = ref(false);
const formtitle = ref("");
const formLabelWidth = "100px";
const form = ref({
  name: "",
  username: "",
  phone: "",
  email: "",
  gender: "",
  status: "",
  deptId: "",
  roleId: "",
  image: "",
  remark: "",
});
const handleAdd = () => {
  dialogFormVisible.value = true;
  formtitle.value = "新增用户";
  form.value = {
    name: "",
    username: "",
    phone: "",
    email: "",
    gender: "",
    status: "",
    deptId: "",
    roleId: "",
    image: "",
    remark: "",
  };
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
};

const save = () => {
  userFormRef.value.validate(async (valid) => {
    let result;
    if (valid) {
      // 设置默认密码：用户名+123
      if (!form.value.id) {
        form.value.password = form.value.username + "123";
      }

      if (form.value.id) {
        result = await updateApi(form.value);
      } else {
        result = await addApi(form.value);
      }
      if (result.code == 1) {
        dialogFormVisible.value = false;
        search();
        ElMessage.success(form.value.id ? "修改成功" : "添加成功");
      } else {
        ElMessage.error(result.msg);
      }
    } else {
      ElMessage.error("请填写正确的信息");
    }
  });
};

const handleDelete = async (id) => {
  ElMessageBox.confirm("您确认要删除该用户吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const result = await deleteApi(id);
    if (result.code == 1) {
      ElMessage.success("删除成功");
      search();
    } else {
      ElMessage.error(result.msg);
    }
  });
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning("请选择要删除的用户");
    return;
  }

  const ids = selectedUsers.value.map((user) => user.id).join(",");
  ElMessageBox.confirm(
    `您确认要删除选中的 ${selectedUsers.value.length} 个用户吗?`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    const result = await deleteApi(ids);
    if (result.code == 1) {
      ElMessage.success("批量删除成功");
      selectedUsers.value = [];
      search();
    } else {
      ElMessage.error(result.msg);
    }
  });
};

// 头像上传
// const handleImageUpload = async (options) => {
//   const file = options.file;
//   try {
//     const result = await uploadImageApi(file);
//     if (result.code == 1) {
//       form.value.image = result.data;
//       ElMessage.success("头像上传成功");
//     } else {
//       ElMessage.error(result.msg || "头像上传失败");
//     }
//   } catch (error) {
//     ElMessage.error("头像上传失败");
//   }
// };

// 头像上传前的验证
const beforeImageUpload = (file) => {
  const isImage =
    file.type === "image/jpeg" ||
    file.type === "image/png" ||
    file.type === "image/jpg";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("头像只能是 PNG/JPG/JPEG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("头像大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 清除头像
const clearImage = () => {
  form.value.image = "";
};

// 添加校验功能
const rules = {
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
    { min: 5, max: 50, message: "长度在 5 到 50 个字符", trigger: "blur" },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
  deptId: [{ required: false, message: "请选择部门", trigger: "blur" }],
  roleId: [{ required: false, message: "请选择角色", trigger: "blur" }],
  remark: [{ max: 200, message: "备注不能超过200个字符", trigger: "blur" }],
};

const userFormRef = ref(null);

// 根据id查询用户
const handleEdit = async (id) => {
  const result = await getByIdApi(id);
  if (result.code == 1) {
    dialogFormVisible.value = true;
    formtitle.value = "修改用户";
    form.value = result.data;
  }
};
</script>

<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <el-form
      :inline="true"
      :model="queryParams"
      ref="queryForm"
      class="search-form"
    >
      <el-form-item label="姓名">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="部门">
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="dept in deptList"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          style="width: 100%"
        >
          <el-option label="正常" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item class="search-buttons">
        <el-button type="primary" @click="search">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="clear">
          <el-icon><Refresh /></el-icon>清空
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加用户
      </el-button>
      <el-button
        type="danger"
        plain
        :disabled="selectedUsers.length === 0"
        @click="handleBatchDelete"
      >
        <el-icon><Delete /></el-icon>批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="userList"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="name" label="姓名" width="120" align="center" />
      <el-table-column
        prop="username"
        label="用户名"
        width="120"
        align="center"
      />
      <el-table-column label="头像" width="80" align="center">
        <template #default="scope">
          <el-avatar
            :size="40"
            :src="scope.row.image"
            :icon="scope.row.image ? undefined : 'UserFilled'"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="deptName"
        label="部门"
        width="150"
        align="center"
      />
      <el-table-column
        prop="roleName"
        label="角色"
        width="150"
        align="center"
      />
      <el-table-column prop="phone" label="手机号" width="130" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? "正常" : "停用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="最后操作时间"
        width="180"
        align="center"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row.id)">
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/修改用户对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="formtitle" width="500">
      <el-form :model="form" :rules="rules" ref="userFormRef">
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
          <el-input
            v-model="form.name"
            autocomplete="off"
            placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item
          label="用户名"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input
            v-model="form.username"
            autocomplete="off"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-input
            v-model="form.phone"
            autocomplete="off"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input
            v-model="form.email"
            autocomplete="off"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option label="正常" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" :label-width="formLabelWidth" prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择">
            <el-option
              v-for="dept in deptList"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <!-- :http-request="handleImageUpload" -->
        <el-form-item label="头像" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            name="image"
            :before-upload="beforeImageUpload"
            action="/api/upload"
            :headers="{ token: token }"
            accept=".png,.jpg,.jpeg"
            :on-success="handleUploadSuccess"
          >
            <img v-if="form.image" :src="form.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            图片上传,支持扩展名: .png/.jpg/.jpeg 大小限制: 2M
          </div>
          <div v-if="form.image" class="image-actions">
            <el-button type="danger" size="small" @click="clearImage"
              >清除头像</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入用户的备注信息,最多200字"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #fff;
  min-height: 100%;
  border-radius: 8px;
}

.operation-area {
  margin: 20px 0;
}

.operation-area .el-button {
  margin-right: 10px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form :deep(.el-form-item) {
  margin-right: 20px;
  min-width: 200px;
}

.search-buttons {
  margin-left: auto !important;
  min-width: auto !important;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  line-height: 1.4;
}

.image-actions {
  margin-top: 8px;
  text-align: center;
}
</style>
